<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>

<%@page import="com.carple.dto.Member"%>

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<meta name="viewport"
	content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<script src="http://maps.google.com/maps/api/js?v=3&amp;sensor=false"></script>
<title>CARSHARING 등록</title>
<link rel="Stylesheet" href="/carple/styles/main.css" />
<link rel="Stylesheet" href="/carple/styles/default.css" />
<link rel="Stylesheet" href="/carple/styles/input.css" />
<script src="/carple/script/OpenLayers.js"></script>

<script type="text/javascript">

	
///////////////////////////////////////////////////////////////////////////////////	

	function checkAndSubmit() {
		var message = "";
		var memberId = document.getElementById("fee");
		if (memberId.value.length == 0) {
			message += "요금을 입력하세요.\r\n";
		}
		var ismarried = document.getElementById("ismarried");
		if (ismarried.value.length == 0) {
			message += "결혼 여부를 선택하세요.\r\n";
		}
//		var coordinates1 = document.getElementById("coordinates1");
//		if (coordinates1.value.length == 0) {
//			message += "첫 번째 좌표를 선택하세요.\r\n";
//		}
		if (message.length > 0) {
			alert(message);
		} else {
			document.getElementById("carsharingregisterform").submit();
		}
	}

	var baseLink = "http://localhost/osm/";
	var multimapBaseLink = "http://www.multimap.com/map/browse.cgi?scale=10000&icon=x";
	var setLat = 37.5583330;
	var setLon = 126.9858000;
	var setZoom = 13;
	var map;
	var projGoogle;
	var projWGS84;
	var markersvector;
///////////////////////////////////////////////////////////////////////////////////////
	var positionindex = 1;
	var limit = 5;
///////////////////////////////////////////////////////////////////////////////////////	
	

	// argItems code taken from 
	// http://www.evolt.org/article/Javascript_to_Parse_URLs_in_the_Browser/17/14435/?format=print
	function argItems(theArgName) {
		sArgs = location.search.slice(1).split('&');
		r = '';
		for (var i = 0; i < sArgs.length; i++) {
			if (sArgs[i].slice(0, sArgs[i].indexOf('=')) == theArgName) {
				r = sArgs[i].slice(sArgs[i].indexOf('=') + 1);
				break;
			}
		}
		return (r.length > 0 ? unescape(r).split(',') : '')
	}

	OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
		defaultHandlerOptions : {
			'single' : true,
			'double' : false,
			'pixelTolerance' : 0,
			'stopSingle' : false,
			'stopDouble' : false
		},

		initialize : function(options) {
			this.handlerOptions = OpenLayers.Util.extend({},
					this.defaultHandlerOptions);
			OpenLayers.Control.prototype.initialize.apply(this, arguments);
			this.handler = new OpenLayers.Handler.Click(this, {
				'click' : this.trigger
			}, this.handlerOptions);
		},

		trigger : function(e) {
			var lonlat = map.getLonLatFromPixel(e.xy);
			var zoom = map.getZoom();
			var vectors = map.getLayersByName('My Location');
			var vector = vectors[0];

			map.setCenter(lonlat, map.getZoom());
			updateLocation(map.getCenter(), map.getZoom());
			placeMark(map.getCenter());
///////////////////////////////////////////////////////////////////////////////////////
			positionindex = positionindex + 1;
///////////////////////////////////////////////////////////////////////////////////////
		}

	});

	function placeMark(lonlat) {
		var markersvectorlayer = map.getLayer('Markersvector');
		markersvectorlayer.removeAllFeatures();
		point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
		markersvectorlayer.addFeatures([ new OpenLayers.Feature.Vector(point,
				{}, {
					graphicName : 'cross',
					strokeColor : '#f00',
					strokeWidth : 2,
					fillOpacity : 0,
					pointRadius : 10
				}) ]);
	}

	function updateLocation(lonlat, zoom) {
///////////////////////////////////////////////////////////////////////////////////////
		if (positionindex > limit) {
			alert("입력 가능한 경로의 갯수를 초과하였습니다.");
			return;
		}
///////////////////////////////////////////////////////////////////////////////////////
		
		// var lonlat = map.getCenter();
		// var zoom = map.getZoom();
		// updateLocation(map.getCenter(), map.getZoom());
		lonlatWGS84 = lonlat.transform(projGoogle, projWGS84);

		var lat = lonlatWGS84.lat;
		var lon = lonlatWGS84.lon;
		var latFixed = lat.toFixed(6);
		var lonFixed = lon.toFixed(6);
		

		var message = "geotagged geo:lat=" + latFixed + " geo:lon=" + lonFixed
				+ " ";
		var messageRoboGEO = latFixed + "," + lonFixed + "";

		document.getElementById("frmLat").value = lat;
		document.getElementById("frmLon").value = lon;
		document.getElementById("geocode").value = message;
///////////////////////////////////////////////////////////////////////////////////////		
		document.getElementById("geocodeRoboGEO" + positionindex).value = messageRoboGEO;
///////////////////////////////////////////////////////////////////////////////////////		
		document.getElementById("geocode").focus();
		document.getElementById("geocode").select();

	}

	function init() {

		map = new OpenLayers.Map("map", {
			projection : new OpenLayers.Projection("EPSG:900913"),
			displayProjection : new OpenLayers.Projection("EPSG:4326")
		});

		projWGS84 = new OpenLayers.Projection("EPSG:4326");
		projGoogle = new OpenLayers.Projection("EPSG:900913");

		var osm = new OpenLayers.Layer.OSM("Open Streetmap");
		osm.setVisibility(true);
		var gmap = new OpenLayers.Layer.Google("Google Streets", {
			visibility : false
		});
		var gmap2 = new OpenLayers.Layer.Google("Google Satellite", {
			type : google.maps.MapTypeId.SATELLITE,
			visibility : false
		});
		var gmap3 = new OpenLayers.Layer.Google("Google Hybrid", {
			type : google.maps.MapTypeId.HYBRID,
			visibility : false
		});
		var gmap4 = new OpenLayers.Layer.Google("Google Terrain", {
			type : google.maps.MapTypeId.TERRAIN,
			visibility : false
		});

		var vector = new OpenLayers.Layer.Vector('My Location');
		markersvector = new OpenLayers.Layer.Vector("My Marker");
		markersvector.id = "Markersvector";

		map
				.addLayers([ osm, gmap, gmap2, gmap3, gmap4, vector,
						markersvector ]);
		map.addControl(new OpenLayers.Control.LayerSwitcher());
		map.addControl(new OpenLayers.Control.Permalink({
			div : maplink
		}));
		map.addControl(new OpenLayers.Control.ScaleLine());
		map.addControl(new OpenLayers.Control.MousePosition({}));

		if (!map.getCenter()) {
			var point = new OpenLayers.LonLat(setLon, setLat);
			map.setCenter(
					point.transform(projWGS84, map.getProjectionObject()),
					setZoom);
			updateLocation(map.getCenter(), map.getZoom());
			placeMark(map.getCenter());
		} else if (argItems("lat") != '' && argItems("lon") != '') {
			var point = new OpenLayers.LonLat(parseFloat(argItems("lon"))
					.toFixed(6), parseFloat(argItems("lat")).toFixed(6));
			map.setCenter(
					point.transform(projWGS84, map.getProjectionObject()),
					setZoom);
			updateLocation(map.getCenter(), map.getZoom());
			placeMark(map.getCenter());

		} else {
			updateLocation(map.getCenter(), map.getZoom());
			placeMark(map.getCenter());
		}

		var click = new OpenLayers.Control.Click();
		map.addControl(click);
		click.activate();

		//
		// 내 위치 찾기
		//
		var pulsate = function(feature) {
			var point = feature.geometry.getCentroid(), bounds = feature.geometry
					.getBounds(), radius = Math
					.abs((bounds.right - bounds.left) / 2), count = 0, grow = 'up';

			var resize = function() {
				if (count > 16) {
					clearInterval(window.resizeInterval);
				}
				var interval = radius * 0.03;
				var ratio = interval / radius;
				switch (count) {
				case 4:
				case 12:
					grow = 'down';
					break;
				case 8:
					grow = 'up';
					break;
				}
				if (grow !== 'up') {
					ratio = -Math.abs(ratio);
				}
				feature.geometry.resize(1 + ratio, point);
				vector.drawFeature(feature);
				count++;
			};
			window.resizeInterval = window.setInterval(resize, 50, point,
					radius);
		};

		var geolocate = new OpenLayers.Control.Geolocate({
			bind : false,
			geolocationOptions : {
				enableHighAccuracy : false,
				maximumAge : 0,
				timeout : 7000
			}
		});

		map.addControl(geolocate);
		var firstGeolocation = true;
		var style = {
			fillColor : '#000',
			fillOpacity : 0.1,
			strokeWidth : 0
		};
		geolocate.events.register("locationupdated", geolocate, function(e) {
			vector.removeAllFeatures();
			var circle = new OpenLayers.Feature.Vector(
					OpenLayers.Geometry.Polygon
							.createRegularPolygon(
									new OpenLayers.Geometry.Point(e.point.x,
											e.point.y),
									e.position.coords.accuracy / 2, 40, 0), {},
					style);
			vector.addFeatures([ new OpenLayers.Feature.Vector(e.point, {}, {
				graphicName : 'cross',
				strokeColor : '#f00',
				strokeWidth : 2,
				fillOpacity : 0,
				pointRadius : 10
			}), circle ]);
			if (firstGeolocation) {
				map.zoomToExtent(vector.getDataExtent());
				pulsate(circle);
				firstGeolocation = false;
				this.bind = true;
				updateLocation(map.getCenter(), map.getZoom());
			}
		});
		geolocate.events.register("locationfailed", this, function() {
			OpenLayers.Console.log('Location detection failed');
		});
		document.getElementById('locate').onclick = function() {
			vector.removeAllFeatures();
			geolocate.deactivate();
			geolocate.watch = false;
			firstGeolocation = true;
			geolocate.activate();

		};
		//
		// 내 위치 찾기
		//
		document.getElementById('setLatLon').onclick = function() {
			var point = new OpenLayers.LonLat(
					document.getElementById('frmLon').value, 
					document.getElementById('frmLat').value);
			map.setCenter(
					point.transform(projWGS84, map.getProjectionObject()), map
							.getZoom());
			updateLocation(map.getCenter(), map.getZoom());
			placeMark(map.getCenter());

		};
	}

	/* 
	function init() {
	    map = new OpenLayers.Map("map");
	    var mapnik         = new OpenLayers.Layer.OSM();
	    var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
	    var toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
	    var position       = new OpenLayers.LonLat(126.9858000,37.5583330).transform( fromProjection, toProjection);
	    var zoom           = 12;
	
	    map.addLayer(mapnik);
	    map.setCenter(position, zoom );
	  }
	 */
</script>
</head>

<body onload="init()">

	<% pageContext.include("/WEB-INF/views/include/header.jsp"); %>
	<br /><br /><br /><br /><br /><br />
	<div id="pageContainer">	
		<div id="inputcontent">
			<br />
			<br />
			<div id="inputmain">
				<div class="inputsubtitle">회원기본정보</div>
				<form id="carsharingregisterform" action="carregister.action" method="post">
					<!-- 상대경로표시 -->
					<table>

						<tr>
							<th>E-Mail(ID)</th>
							<td>
								<%
									String emailId = ((Member) session.getAttribute("loginuser"))
											.getEmailId();
								%>
								<%=emailId%> <input type="hidden" name="emailid"
								value="<%=emailId%>" style="width: 280px">
							</td>
						</tr>

						<tr>
							<th>요금(단위:원)</th>
							<td><input type="text" id="fee" name="fee"
								style="width: 280px" /></td>
						</tr>
						<tr>
							<th>결혼 여부</th>
							<td>미혼<input type="radio" id="ismarried" name="ismarried"
								value="single" style="width: 50px" checked /> 기혼<input
								type="radio" id="ismarried" name="ismarried" value="married"
								style="width: 50px" />
							</td>
						</tr>
						<tr>
							<th>출발지</th>
							<td ><div style="text-align:right"><br />+버튼을 누르면 다양한 지도를 이용할 수 있습니다.</div>
								<div id="map" style="width: 600px; height: 400px"></div>
		                	<!--
		                	<input type="text" id="coordinates1" name="coordinates1" style="width:280px" />
		                	<input type="hidden" name="routeorder1" value="1">
		                	-->
		          

								<div id="geo" style="width: 300px;" class="tekst">
									<input type='hidden' id="frmLat"/>
									<input type='hidden' id="frmLon"/>
									<input type="hidden" id="setLatLon" value="Set">
									<input type="hidden" id="geocode"/>
									<br /><b>내가 클릭한 좌표 </b><br />
									
<!---------------------------------------------geocodeRoboGEO--------------------------------------------------->									
									<input type="text" id="geocodeRoboGEO1" name="coordinates1" readonly="readonly" />
									<input type="hidden" name="routeorder1" value="1" /><br />
									<input type="text" id="geocodeRoboGEO2" name="coordinates2" readonly="readonly" />
									<input type="hidden" name="routeorder2" value="2" /><br />
									<input type="text" id="geocodeRoboGEO3" name="coordinates3" readonly="readonly" />
									<input type="hidden" name="routeorder3" value="3" /><br />
									<input type="text" id="geocodeRoboGEO4" name="coordinates4" readonly="readonly" />
									<input type="hidden" name="routeorder4" value="4" /><br />
									<input type="text" id="geocodeRoboGEO5" name="coordinates5" readonly="readonly" />
									<input type="hidden" name="routeorder5" value="5" /><br />
<!-------------------------------------------------------------------------------------------------------------->							
									
									<input type="hidden" id="maplink"/>
									<br />
									<input type="button" id="locate" value="현재 내 위치로 바로가기!" style="padding:5px;height:30px" />
									<br /><br />
								</div>

							</td>
							</tr>
							
					</table>
					
					<div class="buttons">
						<input type="button" value="등록" style="height: 25px"
							onclick="checkAndSubmit();" /> <input type="button" value="취소"
							style="height: 25px" onclick="location.href='/carple/index.jsp';" />
					</div>
				</form>
			</div>
		</div>

	</div>

</body>
</html>